package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.service.SysRoleUserService;
import com.atguigu.spzx.model.dto.system.SysRoleDto;
import com.atguigu.spzx.model.entity.base.BaseEntity;
import com.atguigu.spzx.model.entity.system.SysRole;
import com.atguigu.spzx.model.entity.system.SysRoleUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.spzx.manager.service.SysRoleService;
import com.atguigu.spzx.manager.mapper.SysRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Windows
 * @description 针对表【sys_role(角色)】的数据库操作Service实现
 * @createDate 2024-01-25 16:52:12
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {

    @Autowired
    private SysRoleUserService sysRoleUserService;

    @Override
    public Page<SysRole> findByPage(SysRoleDto sysRoleDto, Integer pageNum, Integer pageSize) {
        Page<SysRole> page = this.page(new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<SysRole>()
                        .eq(StringUtils.isNotBlank(sysRoleDto.getRoleName()),SysRole::getRoleName, sysRoleDto.getRoleName()));
        return page;
    }

    @Override
    public void saveSysRole(SysRole sysRole) {
        if (!this.save(sysRole)) {
            throw new GuiguException(ResultCodeEnum.INSERT_ERROR);
        }
    }

    @Override
    public void updateSysRole(SysRole sysRole) {
        if (!this.updateById(sysRole)) {
            throw new GuiguException(ResultCodeEnum.UPDATE_ERROR);
        }
    }

    @Override
    public void deleteById(Long roleId) {
        if (!this.removeById(roleId)) {
            throw new GuiguException(ResultCodeEnum.DELETE_ERROR);
        }
    }

    @Override
    public Map<String, Object> findAllRoles(Long userId) {
        // 先用userId查询出这个用户的身份id
        List<Long> roleIdList = sysRoleUserService.list(new LambdaQueryWrapper<SysRoleUser>()
                .eq(SysRoleUser::getUserId, userId))
                .stream().map(SysRoleUser::getRoleId)
                .collect(Collectors.toList());

        List<SysRole> sysRoleList = this.list();
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("allRolesList",sysRoleList);
        resultMap.put("sysUserRoles",roleIdList);
        return resultMap;
    }
}




